/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import SequenceStore from './SequenceStore'
import RepeatedOffsets from './RepeatedOffsets'
import BlockCompressionState from './BlockCompressionState'
import SequenceEncodingContext from './SequenceEncodingContext'
import HuffmanCompressionContext from './HuffmanCompressionContext'
import { CompressionParameters } from './CompressionParameters'
import Constants from './Constants'
import Long from '../util/long/index'

export default class CompressionContext {
    public offsets: RepeatedOffsets = new RepeatedOffsets();
    public blockCompressionState: BlockCompressionState;
    public sequenceStore: SequenceStore;
    public sequenceEncodingContext: SequenceEncodingContext = new SequenceEncodingContext();
    public huffmanContext: HuffmanCompressionContext = new HuffmanCompressionContext();

    constructor(parameters: CompressionParameters, baseAddress: Long, inputSize: number) {
        let windowSize: number = Math.max(1, Math.min(1 << parameters.getWindowLog(), inputSize));
        let blockSize: number = Math.min(Constants.MAX_BLOCK_SIZE, windowSize);
        let divider: number = (parameters.getSearchLength() == 3) ? 3 : 4;

        let maxSequences: number = blockSize / divider;

        this.sequenceStore = new SequenceStore(blockSize, maxSequences);

        this.blockCompressionState = new BlockCompressionState(parameters, baseAddress);
    }

    public commit(): void{
        this.offsets.commit();
        this.huffmanContext.saveChanges();
    }
}
